﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace NewsPortal.Utils.Ciphering
{
    public static class CipheringUtils
    {
        private static SymmetricAlgorithm symAlg;
        

        static CipheringUtils()
        {
            symAlg = SymmetricAlgorithm.Create("AES");
            symAlg.GenerateIV();
            symAlg.GenerateKey();
        }

        public static string EncryptString(string inString)
        {
            byte[] inBlock = Encoding.Unicode.GetBytes(inString);
            ICryptoTransform xfrm = symAlg.CreateEncryptor();
            byte[] outBlock = xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length);

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < outBlock.Length; i++)
            {
                sBuilder.Append(outBlock[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }


        public static string DecryptString(string inString)
        {
            byte[] outBlock;
            try
            {
                ICryptoTransform xfrm = symAlg.CreateDecryptor();
                byte[] inBytes = StringToByteArray(inString);
                outBlock = xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);
            }
            catch (CryptographicException)
            {
                return String.Empty;
            }            
            return Encoding.Unicode.GetString(outBlock);
        }

        public static byte[] StringToByteArray(String hex)
        {
            int numberChars = hex.Length;
            byte[] bytes = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

        public static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
    }
}